package com.ft.adbix.core.interactive;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;

public class DirectionalShakeDetector extends ShakeDetector {

    private OnDirectionalShakeListener onDirectionalShakeListener;

    public DirectionalShakeDetector(Context context) {
        super(context);
    }

    public enum ShakeDirection {
        LEFT, RIGHT, UP, DOWN, FORWARD, BACKWARD
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            float x = event.values[0];
            float y = event.values[1];
            float z = event.values[2];

            ShakeDirection direction = determineDirection(x, y, z);
            if (direction != null && onDirectionalShakeListener != null) {
                onDirectionalShakeListener.onDirectionalShake(direction);
            }
        }
    }

    private ShakeDirection determineDirection(float x, float y, float z) {
        float absX = Math.abs(x);
        float absY = Math.abs(y);
        float absZ = Math.abs(z);

        if (absX > absY && absX > absZ) {
            return x > 0 ? ShakeDirection.RIGHT : ShakeDirection.LEFT;
        } else if (absY > absX && absY > absZ) {
            return y > 0 ? ShakeDirection.UP : ShakeDirection.DOWN;
        } else if (absZ > absX && absZ > absY) {
            return z > 0 ? ShakeDirection.FORWARD : ShakeDirection.BACKWARD;
        }

        return null;
    }

    public void setOnDirectionalShakeListener(OnDirectionalShakeListener onDirectionalShakeListener) {
        this.onDirectionalShakeListener = onDirectionalShakeListener;
    }

    public interface OnDirectionalShakeListener {
        void onDirectionalShake(ShakeDirection direction);
    }
}